'use strict';

const Service = require('egg').Service;
const ulid  = require('../public/ulid');
class MenuService extends Service {
    async findListTree() {
        return await this.ctx.modelmysql.Menu.findAll({
            order: [[ 'sort', 'ASC' ]],
        })
    }
    async findList(module_id) {
        return await this.ctx.modelmysql.Menu.findAll({
          where: {
            module_id,
          },
          order: [[ 'sort', 'ASC' ]],
          include: {
            model: this.ctx.modelmysql.Menu,
          },
        });
      }
    async create(params){
        return await this.ctx.modelmysql.Menu.create({
            id:ulid.ulid(),
            name: params.name,
            module_id: params.moduleID,
            type: params.type,
            sort: params.sort,
            url: params.url,
            description: params.description,
        });
    }
    async edit(params){
        return await this.ctx.modelmysql.Menu.update({
            name: params.name,
            type: params.type,
            sort: params.sort,
            url: params.url,
            description: params.description,
        },{where:{id:params.id}})
    }
    async delete(params){
      return await this.ctx.modelmysql.Menu.destroy({where:{id:params.id}})
    }
    async recombinationMenuTree(dataArr, module_id, treeData = []) {
        for (let i = 0; i < dataArr.length; i++) {
          if (dataArr[i].module_id == module_id) {
            const item = {
              id: dataArr[i].id,
              pid: dataArr[i].module_id,
              name: dataArr[i].name,
              url:dataArr[i].url
            };
    
            const children = await this.recombinationMenuTree(dataArr, item.id); // 继续遍历自己的子菜单
            if (children.length > 0) { // 检查是否存在子菜单
              item.children = children;
            }
            treeData.push(item);
          }
        }
        return treeData;
      }
    async findById(params){
        return await this.ctx.modelmysql.Menu.findOne({
            where:{id:params.id}
        })
    }
}

module.exports = MenuService;
